import {constantRouterMap} from '@/router/routers'
import Layout from '@/layout/index'

const permission = {
  state: {
    routers: constantRouterMap,
    filterRouter: [],
    subRoutes: [],
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    },
    SET_CHILDREN_ROUTERS: (state, routers) => {
      state.filterRouter = routers
      localStorage.setItem('filterRouter', JSON.stringify(routers))
    }
  },
  actions: {
    GenerateRoutes({commit}, asyncRouter) {
      commit('SET_ROUTERS', asyncRouter)
    },
    updateRoute({commit}, children) {
      commit('SET_CHILDREN_ROUTERS', children)
    }
  }
}

const _import = require('@/router/config/_import_' + process.env.NODE_ENV)
// 微前端每个模块要有单独的前缀
const prefix = process.env.VUE_APP_BASE_PATH
const page404 = _import('features/404')
export const filterAsyncRouter = (routers) => { // 遍历后台传来的路由字符串，转换为组件对象
  return routers.filter(router => {
    const keys = ['path', 'name', 'children', 'component', 'hidden', 'icon', 'cache', 'code', 'iframe']
    for (const key in router.data) {
      if (keys.includes(key)) {
        router[key] = router.data[key]
      }
    }
    router.data = null
    if (router.component) {
      if (router.component === 'Layout') { // Layout组件特殊处理
        router.component = Layout
      } else {
        const component = router.component
        try {
          router.component = _import(component)
        } catch (e) {
          router.component = page404
        }
      }
    } else {
      router.component = Layout
    }
    router.meta = {title: router.name, icon: router.icon}
    router.name = router.code
    if (router.children && router.children.length) {
      router.children = filterAsyncRouter(router.children)
    } else {
      router.children = []
    }

    // 以微前端启动，统一加上前缀
    if (window.__POWERED_BY_QIANKUN__) {
      if (router.path && !router.path.startsWith(prefix) && router.path.startsWith("/") && router.path != '/') {
        router.path = prefix + router.path
      }
    }
    return true
  })
}

export default permission
